/**
 * Created by chenyong on 2015/11/14.
 */

/*
用户标注点
 */
var UserTags = function(panoId){
    this.panoId = "";
    if (arguments.length === 1)
    {
        this.panoId = panoId;
    }

    this.arrTags = [];
    this.tagsvisible = true;

    self = this;

    //当接收到随机的标注点时触发
    var _onReceivedRandomTagsEvent;
    var limit = 100;
    var skip = 0;
    var sure_trigger=false;

    this.tagworker = new Worker("/scripts/worker/usertag-worker.js");
    this.tagworker.onerror = function(event){
        console.log(event);
    }
    this.tagworker.onmessage = function(event){
        //返回标注点列表
        if(event.data.msgtype && event.data.msgtype == "getusertags")
        {
            var data = event.data.list;
            //移除现有标注点
            for(var i=0;i<self.arrTags.length;i++)
            {
                var _taginfo = self.arrTags[i];
                //bpsviewer.call('removehotspot('+_taginfo.id+');');
                //bpsviewer.call('removeplugin('+_taginfo.id+'_url'+');');
                //bpsviewer.call('removeplugin('+ _taginfo.id+'_name'+');');
            }
            self.arrTags = [];
            //添加标注点
            for(var i=0;i<data.length;i++){
                self.arrTags.push(data[i]);
                self.createTag(data[i]);
            }
            if(event.data.total > (event.data.skip + limit))
            {
                skip = skip + limit;
            }
            else
            {
                skip = 0;
            }
        }
        if(event.data.msgtype && event.data.msgtype == "getusertags-error")
        {
            setTimeout("self.getUserTagsDataWorker();",2000);
        }
        //getusertags-error

        //返回随机标注点
        if(event.data.msgtype && event.data.msgtype == "randomusertags")
        {
            var data = event.data.list;
            if(typeof(_onReceivedRandomTagsEvent) == "function" )
            {
                _onReceivedRandomTagsEvent.call(null,data);
            }
        }

    }

    var setTagVisible = function(taginfo,visibility)
    {
        taginfo.visible=visibility;
        bpsviewer.set('hotspot['+taginfo.id+'].visible',visibility);
    }

    this.OnReceivedRandomTags = function(func)
    {
        _onReceivedRandomTagsEvent = func;
    }
    this.refreshTags = function(){
        var fov = bpsviewer.get("view.fov");
        $.each(self.arrTags,function(i,taginfo){
            var visible = self.tagsvisible;
            var zoomlevel = taginfo.fov / fov;
            if(zoomlevel >1.8 || zoomlevel < 0.5)
            {
                visible = false;
            }

            if(visible){
                if(!taginfo.visible){
                    setTagVisible(taginfo,true);
                }
            }
            else{
                setTagVisible(taginfo,false);
            }
        });
    }

//转换TagInfo格式
    function convertTaginfo(data)
    {
        var _taginfo = {};
        _taginfo.id = "usertag" + data._id;
        _taginfo.ath = data.ath;
        _taginfo.atv = data.atv;
        _taginfo.fov = data.fov;
        if(typeof(data.userinfo) == "object" )
        {
            _taginfo.avatarurl =  data.userinfo.headimgurl;
        }
        else
        {
            _taginfo.avatarurl = "/images/noavatar@96x96.jpg";
        }

        _taginfo.title = data.title;
        _taginfo.note = data.note;

      if(data.attached != undefined && typeof(data.attached) == "string")
      {
        _taginfo.attached = JSON.parse(data.attached);
      }
      else if (data.attached != undefined && typeof(data.attached == "object") )
      {
        _taginfo.attached = data.attached;
      }
        return _taginfo;
    }

    //从后台读取数据添加用户标注点到视图中
    this.createTag = function(taginfo)
    {
        //console.log(taginfo);
        var tagid = taginfo.id;
        var tag_url = "http://cdn.bigpixel.cn/gpx/ngrunning/usertag_bg01.png";
        if(typeof(taginfo.attached) == 'object' )
        {
            tag_url = "http://cdn.bigpixel.cn/gpx/ngrunning/usertag_bg02.png";
        }
        bpsviewer.call('addhotspot('+tagid+');');
        bpsviewer.set('hotspot['+tagid+'].url',tag_url);
        bpsviewer.set('hotspot['+tagid+'].visible',true);
        bpsviewer.set('hotspot['+tagid+'].ath',taginfo.ath);
        bpsviewer.set('hotspot['+tagid+'].atv',taginfo.atv);
        bpsviewer.set('hotspot['+tagid+'].edge',"bottom");
        bpsviewer.set('hotspot['+tagid+'].zoom',true);
        bpsviewer.set('hotspot['+tagid+'].scale',0.02);

        bpsviewer.set('hotspot['+tagid+'].title',taginfo.title);
        bpsviewer.set('hotspot['+tagid+'].note',taginfo.note);
        bpsviewer.set('hotspot['+tagid+'].avatarurl',taginfo.avatarurl);



        if(taginfo.attached != undefined && typeof(taginfo.attached == "object") && taginfo.attached.code != undefined )
        {

            bpsviewer.set('hotspot['+tagid+'].code',taginfo.attached.code);      //跑者的编号
            bpsviewer.set('hotspot['+tagid+'].crop1','1|627|318|112');      //跑者点击背景
            bpsviewer.set('hotspot['+tagid+'].css1','text-align:left; padding-left:62px;padding-top:15px; color:#ffffff; font-family:Arial; font-size:18px;'); //跑者说的话
        }else{
            bpsviewer.set('hotspot['+tagid+'].code','');      //跑者的编号
            bpsviewer.set('hotspot['+tagid+'].crop1','0|513|318|112');      //跑者点击背景
            bpsviewer.set('hotspot['+tagid+'].css1','text-align:left; padding-left:62px;padding-top:15px; color:#000000; font-family:Arial; font-size:18px;'); //跑者说的话
        }
        bpsviewer.set('hotspot['+tagid+'].onclick','showtaginfo(\''+tagid + '\')');
        if(sure_trigger){
            bpsviewer.call('showtaginfo(\''+tagid + '\')');
            sure_trigger=false;
        }
    }
    //创建用户标注点成功后执行，在这里绑定当前id到链接上
    this.CreateUsertagSuccess = function(taginfo)
    {
        sure_trigger=true;
        this.createTag(convertTaginfo(taginfo));
        self.arrTags.push(taginfo);
        bpsviewer.call("set(hotspot[tagger].visible,false);");
        $(".wx_y").slideUp(100);
        bpsviewer.call('set(plugin[tag_home_btn].visible,true);');
    }

    /**
     * 保存新增加的用户标注点
     */
    this.saveNewtag = function(note,attached)
    {
        if($.bigpixel.isLoggedIn()){
            var data = {
                userid:$.currentUser._id,
                ath:bpsviewer.get('hotspot[tagger].ath'),
                atv:bpsviewer.get('hotspot[tagger].atv'),
                fov:bpsviewer.get('hotspot[tagger].fov') || 10,
                note:note,
              attached:JSON.stringify(attached)

            };

            //如果当前用户已经有标注点，则修改标注点信息，否则创建新的标注点
            this.getTaginfoByUserId(data.userid,function(taginfo){
                if(taginfo != null)
                {
                    //修改标注点
                    var tagid =  taginfo.id.replace("usertag", "");
                    var _url = "/service/panos/" + self.panoId + "/usertags/"+tagid;
                    $.bigpixel.AjaxPutData(_url,data,function(err,data){
                        if(!err)
                        {
                            self.CreateUsertagSuccess(data);
                        }
                    });
                }
                else
                {
                    //新增标注点
                    var _url = "/service/panos/" + self.panoId + "/usertags";
                    $.bigpixel.AjaxPostData(_url,data,function(err,data){
                        if(!err)
                        {
                            self.CreateUsertagSuccess(data);
                        }
                    });
                }
            })
        }
        else
        {
            console.log("请登录");
        }
    }

    //
    this.getUserTagsDataWorker = function(){
        var eventdata = {
            msgtype:"getusertags",
            panoid:self.panoId,
            limit:limit,
            skip:skip,
            gendar:""
        };
        self.tagworker.postMessage(eventdata);
    }
    //从这里 可以成功返回随机标注点得到返回data数据
    this.getRandomTagsDataWorker = function(){

      var count = 4;
      var devicewidth = document.documentElement.clientWidth;
      if (devicewidth >= 360 && devicewidth < 450)
      {
        count = 6;
      }
      else if (devicewidth >= 450)
      {
        count = 8;
      }

        var eventdata = {
            msgtype:"randomusertags",
            panoid:self.panoId,
            count:count
        };
        self.tagworker.postMessage(eventdata);

    }

    //隐藏所有标签
    this.hide_alltags=function(){
      for(var i=0;i<self.arrTags.length;i++){
        setTagVisible(self.arrTags[i],false);
      }
    }

    //显示所有标签
    this.show_alltags=function(){
      for(var i=0;i<self.arrTags.length;i++){
        setTagVisible(self.arrTags[i],true);
      }
    }

    this.isExistsTag = function(taginfo){
        console.log(self.arrTags.length);
        for(var i=0;i<self.arrTags.length;i++){
            if(taginfo.id==self.arrTags[i].id){
                return true;
            }
        }
        return false;
    }

    //旋转到标注点
    this.looktoTag=function(taginfo)
    {
        var arrTags_flag=false;
        $(".fans_list_box").css("display","none");
        bpsviewer.call("set(plugin[cover_hei].visible,false);");

        if(!self.isExistsTag(taginfo)){
            console.log("not exists Push ---------begin");
            console.log(taginfo);
            self.arrTags.push(taginfo);  //push到数组里
            self.createTag(taginfo);   //生成一个新的tag标签

            console.log("not exists Push ---------end");
        }
        bpsviewer.call("showtaginfo(" + taginfo.id + ");");
        bpsviewer.call("zoomto(60,linear(50));moveto("+taginfo.ath+","+taginfo.atv+",linear(60));Wait(0.5);zoomto(1,linear(50));");

    }
    //根据user_id得到相应的信息
    this.getTaginfoByUserId = function(uid,cb)
    {
        var _url = "/service/panos/" + self.panoId + "/usertags?userid="+uid;
        $.bigpixel.AjaxGetJson(_url,function(err,body){
            var data = body.data;

            if(!err && data.length > 0)
            {
                var _taginfo = convertTaginfo(data[0]);
                cb(_taginfo);
            }
            else
            {
                cb(null);
            }
        });
    }

    /**
     * 初始化
     * @constructor
     */
    this.Init = function(panoId)
    {
        self.panoId = panoId;
        //self.getUserTagsDataWorker();
        self.getRandomTagsDataWorker();

    }

    // //显示标注自己想说的话的input框-start
    this.showdialog=function(){
        if( $.bigpixel.isLoggedIn())
        {
            $(".wx_y").slideDown(100);
            var atv = Number( bpsviewer.get("view.vlookat") );
            var ath   = Number( bpsviewer.get("view.hlookat") );
            bpsviewer.call("set(hotspot[tagger].visible,true);");
            bpsviewer.call("set(hotspot[tagger].ath,"+ath+");");
            bpsviewer.call("set(hotspot[tagger].atv,"+atv+");");
            bpsviewer.call("set(plugin[user_name].html,"+ $.currentUser.nickname+");");
            bpsviewer.call("set(plugin[usericon_avatar].url,"+ $.currentUser.avatarurl+");");
        }
        else
        {
            $(".wx_n").slideDown(100);
        }
        bpsviewer.call("set(plugin[tag_home_btn].visible,false);");
    }

    //生成女粉丝列表
    this.create_female_list=function(){
        var woman_fans_html='';
        var limit_num=6;
        var Tag_index=woman_page*limit_num;
        //var _url = "/service/panos/nacc20151114/fans?skip="+woman_page+"&limit=6&sex=2";
        var _url = "/service/panos/" + self.panoId + "/usertags?skip="+Tag_index+"&limit="+limit_num+"&gendar=2";
        $.bigpixel.AjaxGetJson(_url,function(err,data){
            if(!err)
            {
                var TagsDate=data.data;
                var len=TagsDate.length;
                if(len!=0){
                    for(var i=0;i<len;i++)
                    {
                        var _taginfo = convertTaginfo(TagsDate[i]);


                        var strtaginfo = JSON.stringify(_taginfo);
                        var usename=TagsDate[i].userinfo.nickname;
                        woman_fans_html+=  '<li><div class="fans_head_img fl"><img src="'+TagsDate[i].userinfo.headimgurl.replace("/0","/96")+'"/></div>\
					<div class="fans_text fl"><p class="nickname">'+usename+'</p><p class="text">'+TagsDate[i].note+'</p></div>\
					<div class="fans_tag_area fr"><a class="zoom_self fl" href="javascript:void(0);" onclick=\'bpsviewer.UserTags.looktoTag(' + strtaginfo + ')\'>\
					<span class="icon-crosshairs"></span></a></div></li>';
                    }
                    $("#fans_list_woman").append(woman_fans_html  );
                    var list_woman_h=parseInt($("#fans_list_woman").height());
                    if(list_woman_h>300){
                        $(".pullUp_woman").css("display","table");
                        pullUp_woman_flag=true;
                        $(".pullUp_woman .pullUpLabel").html('加载更多...');
                    }else{ $(".pullUp_woman").css("display","none"); }
                }else{
                    if(woman_page==0){
                        $(".pullUp_woman").css("display","table");
                        pullUp_woman_flag=true;
                        $(".pullUp_woman .pullUpLabel").html('还没有更多女粉丝，来抢沙发吧');
                    }else{
                        $(".pullUp_woman").css("display","none");
                    }
                }
                $(".pullUp_woman").removeClass('loading');
            }
        });
        woman_flag=false;
    }
    //生成男粉丝列表
    this.create_male_list=function(){
        var man_fans_html='';
        //var _url = "/service/panos/" + self.panoId + "/fans?skip="+man_page+"&limit=6&sex=1";
        var limit_num=6;
        var Tag_index=man_page*limit_num;
        var _url = "/service/panos/" + self.panoId + "/usertags?skip="+Tag_index+"&limit="+limit_num+"&gendar=1";
        $.bigpixel.AjaxGetJson(_url,function(err,data){
            if(!err)
            {
                var TagsDate=data.data;
                var len=TagsDate.length;
                if(len!=0){
                   // console.log(JSON.stringify(data));
                    for(var i=0;i<len;i++)
                    {
                        var _taginfo = convertTaginfo(TagsDate[i]);
                        var strtaginfo = JSON.stringify(_taginfo);
                        var usename=TagsDate[i].userinfo.nickname;
                        //console.log(i+'='+usename);
                        man_fans_html+=  '<li><div class="fans_head_img fl"><img src="'+TagsDate[i].userinfo.headimgurl+'"/></div>\
					<div class="fans_text fl"><p class="nickname">'+usename+'</p><p class="text">'+TagsDate[i].note+'</p></div>\
					<div class="fans_tag_area fr"><a class="zoom_self fl" href="javascript:void(0);" onclick=\'bpsviewer.UserTags.looktoTag(' + strtaginfo + ')\'>\
					<span class="icon-crosshairs"></span></a></div></li>';
                    }

                    $("#fans_list_man").append(man_fans_html  );
                    var list_woman_h=parseInt($("#fans_list_man").height());
                    if(list_woman_h>300){
                        $(".pullUp_man").css("display","table");
                        pullUp_man_flag=true;
                        $(".pullUp_man .pullUpLabel").html('加载更多...');
                    }else{ $(".pullUp_man").css("display","none"); }
                }else{
                    if(man_page==0){
                        $(".pullUp_man").css("display","table");
                        pullUp_man_flag=true;
                        $(".pullUp_man .pullUpLabel").html('还没有更多男粉丝，来抢沙发吧');
                    }else{
                        $(".pullUp_man").css("display","none");
                    }
                }
                $(".pullUp_man").removeClass('loading');
            }
        });
        man_flag=false;
    }

    //zoom到一个地方去
    this.zoom_go=function(x1,y1,fov){
        $(".fans_list_box").css("display","none");
        bpsviewer.call("set(plugin[cover_hei].visible,false);");
        //bpsviewer.call("zoomto(70,linear(50));moveto("+x1+","+y1+",linear(60));Wait(0.5);zoomto("+fov+",linear(50));");
        bpsviewer.call("moveto("+x1+","+y1+",linear(60));Wait(0.5);zoomto("+fov+",linear(50));");
    }

}
